package com.ruoyi.system.service.impl;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.file.FileTypeUtils;
import com.ruoyi.common.core.utils.file.FileUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.utils.DictUtils;
import com.ruoyi.system.api.domain.ShProductPicture;
import com.ruoyi.system.api.domain.SysDictData;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.domain.ShProductTj;
import com.ruoyi.system.mapper.ShProductPictureMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.utils.TencentUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.ShProductMapper;
import com.ruoyi.system.domain.ShProduct;
import com.ruoyi.system.service.IShProductService;

import javax.annotation.Resource;

/**
 * 商品信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-07-18
 */
@Service
public class ShProductServiceImpl implements IShProductService 
{
    @Autowired
    private ShProductMapper shProductMapper;

    @Autowired
    private ShProductPictureMapper shProductPictureMapper;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Resource
    private StringRedisTemplate myRedisTemplate;

    @Autowired
    private RedisService redisService;

    /**
     * 查询商品信息
     * 
     * @param id 商品信息主键
     * @return 商品信息
     */
    @Override
    public ShProduct selectShProductById(Long id)
    {
        return shProductMapper.selectShProductById(id);
    }

    /**
     * 查询商品信息列表
     * 
     * @param shProduct 商品信息
     * @return 商品信息
     */
    @Override
    public List<ShProduct> selectShProductList(ShProduct shProduct)
    {
        List<ShProduct> list = shProductMapper.selectShProductList(shProduct);
        HashMap<Long, String> schoolMap = sysDeptService.getShopMap();
        List<SysDictData> dictSList = DictUtils.getDictCache("product_label");
        HashMap<String, String> dictSMap = new HashMap<>();
        for (SysDictData data:dictSList) {
            dictSMap.put(data.getDictValue(),data.getDictLabel());
        }
        for (ShProduct obj : list) {
            SysUser sysUser = sysUserMapper.selectUserById(obj.getUserId());
            obj.setUserName(sysUser.getUserName());
            obj.setUserPic(sysUser.getAvatar());
            ShProductPicture paramPic = new ShProductPicture();
            paramPic.setProductId(obj.getId());
            paramPic.setIsVideo(0);
            List<ShProductPicture> picList = shProductPictureMapper.selectShProductPictureList(paramPic);
            obj.setPicList(picList);
            if (null != picList && picList.size() > 0) {
                obj.setPicId(picList.get(0).getId());
                obj.setFileFj(picList.get(0).getProductPic());
            }
            if (null!=shProduct&&null!=shProduct.getIsVideo()&&shProduct.getIsVideo()==1) {
                ShProductPicture paramVid = new ShProductPicture();
                paramVid.setProductId(obj.getId());
                paramVid.setIsVideo(1);
                List<ShProductPicture> vidList = shProductPictureMapper.selectShProductPictureList(paramPic);
                obj.setVidList(vidList);
                if (null != vidList && vidList.size() > 0) {
                    obj.setVidId(vidList.get(0).getId());
                    obj.setVidUrl(vidList.get(0).getProductPic());
                }
            }
            StringBuffer labelName = new StringBuffer();
            if (null != obj.getLabelId() && !"".equals(obj.getLabelId())) {
                String[] labelIdAry = obj.getLabelId().split(",");
                for (String labelId : labelIdAry) {
                    labelName.append(dictSMap.get(labelId)).append(",");
                }
            }
            if (null!=schoolMap) {
                obj.setShopName(schoolMap.get(obj.getShopId()));
            }
            obj.setLabelName(labelName.toString());
        }
        return list;
    }

    @Override
    public List<ShProductTj> selectProductTjList(ShProduct shProduct)
    {
        return shProductMapper.selectProductTjList(shProduct);
    }

    @Override
    public List<ShProductTj> selectProductTjPayList(ShProduct shProduct)
    {
        return shProductMapper.selectProductTjPayList(shProduct);
    }

    /**
     * 新增商品信息
     * 
     * @param shProduct 商品信息
     * @return 结果
     */
    @Override
    public int insertShProduct(ShProduct shProduct)
    {
        shProduct.setCreateTime(DateUtils.getNowDate());
        redisService.delCacheMap("PRODUCT:DP");
        redisService.delCacheMap("PRODUCTTYPE");
        redisService.delCacheMap("MEALTYPE");
        return shProductMapper.insertShProduct(shProduct);
    }

    /**
     * 修改商品信息
     * 
     * @param shProduct 商品信息
     * @return 结果
     */
    @Override
    public int updateShProduct(ShProduct shProduct)
    {
        redisService.delCacheMap("PRODUCT:DP");
        redisService.delCacheMap("PRODUCTTYPE");
        redisService.delCacheMap("MEALTYPE");
        return shProductMapper.updateShProduct(shProduct);
    }

    /**
     * 批量删除商品信息
     * 
     * @param ids 需要删除的商品信息主键
     * @return 结果
     */
    @Override
    public int deleteShProductByIds(Long[] ids)
    {
        redisService.delCacheMap("PRODUCT:DP");
        redisService.delCacheMap("PRODUCTTYPE");
        redisService.delCacheMap("MEALTYPE");
        TencentUtils tencentUtils = TencentUtils.getInstance();
        for (Long id:ids) {
            ShProductPicture paramPic = new ShProductPicture();
            paramPic.setProductId(id);
            List<ShProductPicture> picList = shProductPictureMapper.selectShProductPictureList(paramPic);
            for (ShProductPicture pic:picList) {
                if (null != pic.getProductPic() && pic.getProductPic().indexOf("aliyuncs.com/") > 0) {
                    String[] keyAry = pic.getProductPic().split("aliyuncs.com/");
                    tencentUtils.del(keyAry[1]);
                }
                shProductPictureMapper.deleteShProductPictureById(id);
            }
        }
        return shProductMapper.deleteShProductByIds(ids);
    }

    /**
     * 删除商品信息信息
     * 
     * @param id 商品信息主键
     * @return 结果
     */
    @Override
    public int deleteShProductById(Long id)
    {
        redisService.delCacheMap("PRODUCT:DP");
        redisService.delCacheMap("PRODUCTTYPE");
        redisService.delCacheMap("MEALTYPE");
        TencentUtils tencentUtils = TencentUtils.getInstance();
        ShProductPicture paramPic = new ShProductPicture();
        paramPic.setProductId(id);
        List<ShProductPicture> picList = shProductPictureMapper.selectShProductPictureList(paramPic);
        for (ShProductPicture pic:picList) {
            if (null != pic.getProductPic() && pic.getProductPic().indexOf("aliyuncs.com/") > 0) {
                String[] keyAry = pic.getProductPic().split("aliyuncs.com/");
                tencentUtils.del(keyAry[1]);
            }
            shProductPictureMapper.deleteShProductPictureById(id);
        }
        return shProductMapper.deleteShProductById(id);
    }

    @Override
    public byte[] downloadCode(ShProduct shProduct)throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        List<ShProduct> list = shProductMapper.selectShProductList(shProduct);
        DataOutputStream os = null;
        int num = 1;
        for (ShProduct obj : list) {
            ShProductPicture paramPic = new ShProductPicture();
            paramPic.setProductId(obj.getId());
            paramPic.setIsVideo(0);
            List<ShProductPicture> picList = shProductPictureMapper.selectShProductPictureList(paramPic);
            int numPic = 1;
            for (ShProductPicture pic:picList) {
                if (StringUtils.isEmpty(pic.getProductPic())) {
                    continue;
                }
                String suffix = FileTypeUtils.getFileType(pic.getProductPic());
                boolean isAllow = FileTypeUtils.isAllowedExtension(suffix.toLowerCase(),FileTypeUtils.IMAGE_EXTENSION);
                if (isAllow) {
                    String fileName = num+"-"+numPic+"."+suffix;
                    numPic++;
                    File file = new File("");
                    try {
                        URL url = new URL(pic.getProductPic());
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        conn.setRequestMethod("GET");
                        conn.setConnectTimeout(5000);
                        InputStream is = conn.getInputStream();
                        file = FileUtils.inputStreamToFile(is, fileName);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (file.exists()) {
                        try {
                            assert zip != null;
                            zip.putNextEntry(new ZipEntry(fileName));
                            os = new DataOutputStream(zip);
                            InputStream is = new FileInputStream(file);
                            byte[] b = new byte[100];
                            int length = 0;
                            while ((length = is.read(b)) != -1) {
                                os.write(b, 0, length);
                            }
                            is.close();
                            zip.closeEntry();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            num++;
        }
        IOUtils.closeQuietly(zip);
        if (os != null) {
            os.flush();
            os.close();
        }
        if (zip != null) {
            zip.close();
        }
        return outputStream.toByteArray();
    }

    @Override
    public HashMap<Long, String> getProductMap() {
        Map<Object, Object> mapProductValue = myRedisTemplate.opsForHash().entries("PRODUCT:DP");
        List<ShProduct> productList = null;
        if (null == mapProductValue.get("ALL")||(null!=mapProductValue.get("ALL")&&"[]".equals(mapProductValue.get("ALL").toString()))||mapProductValue.size()<=0) {
            productList = shProductMapper.selectShProductList(new ShProduct());
            Map<String, String> map = new HashMap<>();
            map.put("ALL", JSON.toJSONString(productList));
            myRedisTemplate.opsForHash().putAll("PRODUCT:DP", map);
        } else {
            Object jsonArray = JSON.parse(mapProductValue.get("ALL").toString());
            productList = JSON.parseArray(jsonArray.toString(), ShProduct.class);
        }
        HashMap<Long, String> productNameMap = new HashMap<>();
        for (ShProduct obj : productList) {
            productNameMap.put(obj.getId(), obj.getProductTitle());
        }
        return productNameMap;
    }
}
